package 二叉树相关问题.层次遍历;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 层数最深叶子节点的和 {

    public int deepestLeavesSum(TreeNode root) {
        LinkedList<List<Integer>> lists = new LinkedList<>();
        if (root==null)
            return 0;
        Queue<TreeNode> q =new LinkedList();
        q.offer(root);
        while (!q.isEmpty()){
            List<Integer> list = new LinkedList<>();
            for (int i = q.size(); i >0 ; i--) {
                TreeNode poll = q.poll();
                list.add(poll.val);
                if (poll.left!=null)
                    q.offer(poll.left);
                if (poll.right!=null)
                    q.offer(poll.right);
            }
            lists.add(new ArrayList<>(list));
        }
        List<Integer> res = lists.removeLast();
        int n=0;
        for (Integer i : res) {
            n+=i;
        }
        return n;
    }
}
